package com.qijian.common.utils;

/**
 * 版本号处理
 *
 * @author qijian
 */
public class VersionUtils {

    /**
     * 版本号比较
     * @param version1 /
     * @param version2 /
     * @return /
     */
    public static int versionCompare(String version1, String version2) {
        String[] versionArr1 = version1.split("\\.");
        String[] versionArr2 = version2.split("\\.");
        int minLen = Math.min(versionArr1.length, versionArr2.length);
        int diff = 0;
        for (int i = 0; i < minLen; i++) {
            String v1 = versionArr1[i];
            String v2 = versionArr2[i];
            diff = v1.length() - v2.length();
            if (diff == 0) {
                diff = v1.compareTo(v2);
            }
            if (diff != 0) {
                break;
            }
        }
        diff = (diff != 0) ? diff : (versionArr1.length - versionArr2.length);
        return diff;
    }

    /**
     * 自动升级版本号，版本号+1
     *
     * @param version /
     * @return String
     */
    public static String autoUpgradeVersion(String version) {
        if (version.equals("")) {
            version = "0.0.0.0";
        }
        //将版本号拆解成整数数组
        String[] arr = version.split("\\.");
        int[] ints = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            ints[i] = Integer.parseInt(arr[i]);
        }

        //递归调用
        VersionUtils.autoUpgradeVersion(ints, ints.length - 1);

        //数组转字符串
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ints.length; i++) {
            sb.append(ints[i]);
            if ((i + 1) != ints.length) {
                sb.append(".");
            }
        }
        return sb.toString();
    }

    /**
     * 自动升级版本号，版本号+1
     *
     * @param ints  /
     * @param index /
     */
    public static void autoUpgradeVersion(int[] ints, int index) {
        if (index == 0) {
            ints[0] = ints[0] + 1;
        } else {
            int value = ints[index] + 1;
            if (value < 10) {
                ints[index] = value;
            } else {
                ints[index] = 0;
                autoUpgradeVersion(ints, index - 1);
            }
        }
    }
}
